package net.didactylos.helpline.action;

import org.hibernate.Session;

import net.didactylos.helpline.data.Template;
import net.didactylos.helpline.stripes.bean.HelplineActionBean;
import net.didactylos.helpline.stripes.security.Capabilities;
import net.didactylos.helpline.stripes.security.Secured;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.controller.*;
import net.sourceforge.stripes.validation.*;

public class TemplateAction extends HelplineActionBean
{
	@ValidateNestedProperties({
		@Validate(field="fromName", maxlength=50),
		@Validate(field="fromAddress", required=true, maxlength=50, converter=EmailTypeConverter.class),
		@Validate(field="header", maxlength=3000),
		@Validate(field="footer", maxlength=3000)
	})
	private Template template;

	public Template getTemplate()
	{
		return template;
	}

	public void setTemplate(Template template)
	{
		this.template = template;
	}
	
	@Before(stages=LifecycleStage.BindingAndValidation)
	public void preLoad()
	{
		Session session = getContext().getSession();
		template = (Template) session.createCriteria(Template.class).uniqueResult();
		if (template == null)
		{
			template = new Template();
		}
	}
	
	@DontValidate
	@DefaultHandler
	@Secured(Capabilities.SIGN_IN)
	public Resolution view()
	{
		return new ForwardResolution("settings.jspx");
	}
	
	@Secured(Capabilities.SIGN_IN)
	public Resolution edit()
	{
		Session session = getContext().getSession();
		session.saveOrUpdate(template);
        
        getContext().getMessages().add(new LocalizableMessage("editTemplateMessage"));

		return new RedirectResolution(TemplateAction.class);
	}
	
}
